package com.haidechizi.fastadmin.modules.oss.cloud;


import com.haidechizi.fastadmin.common.exception.BusinessException;
import com.haidechizi.fastadmin.common.utils.ConfigConstant;
import com.haidechizi.fastadmin.common.utils.Constant;
import com.haidechizi.fastadmin.common.utils.GlobalUtils;
import com.haidechizi.fastadmin.common.utils.SpringContextHolder;
import com.haidechizi.fastadmin.modules.sys.service.SysConfigService;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传Factory
 */
public final class OSSFactory {
    private static SysConfigService sysConfigService;

    private static Map<Integer, Class<? extends CloudStorageService>> cloudStorageServiceHolder = new HashMap<>(8);

    static {
        OSSFactory.sysConfigService = SpringContextHolder.getBean(SysConfigService.class);

        // 将所有CloudStorageService放入到Map中
        cloudStorageServiceHolder.put(Constant.CloudService.QINIU.getValue(), QiniuCloudStorageService.class);
        cloudStorageServiceHolder.put(Constant.CloudService.ALIYUN.getValue(), AliyunCloudStorageService.class);
        cloudStorageServiceHolder.put(Constant.CloudService.QCLOUD.getValue(), QcloudCloudStorageService.class);
        cloudStorageServiceHolder.put(Constant.CloudService.LOCAL.getValue(), LocalStorageService.class);
    }

    public static CloudStorageService build() {
        // 使用本地文件存储
        if ("1".equals(GlobalUtils.fileStorageType())) {
            Class<? extends CloudStorageService> clazz = cloudStorageServiceHolder.get(Constant.CloudService.LOCAL.getValue());
            try {
                Constructor constructor = clazz.getConstructor();
                return (CloudStorageService) constructor.newInstance();
            } catch (Exception e) {
                throw new BusinessException("反射创建类失败", e);
            }
        }
        //获取云存储配置信息
        CloudStorageConfig config = sysConfigService.getConfigObject(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY, CloudStorageConfig.class);

        if (!cloudStorageServiceHolder.containsKey(config.getType())) {
            throw new BusinessException("请配置文件上传类");
        }
        Class<? extends CloudStorageService> clazz = cloudStorageServiceHolder.get(config.getType());
        try {
            Constructor constructor = clazz.getConstructor(CloudStorageConfig.class);
            return (CloudStorageService) constructor.newInstance(config);
        } catch (Exception e) {
            throw new BusinessException("反射创建类失败", e);
        }
    }

}
